package org.orm.oop.common.util;

import lombok.extern.slf4j.Slf4j;
import org.orm.oop.common.CommonConstants;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class FileUtils {
    /**
     * 查询某个目录下所有文件
     * @return
     */
    public static List<File> findAllByDir(String dir) {
        List<File> files = new ArrayList<>();
        if(!StringUtils.isEmpty(dir)) {
            recursiveFind(files, dir);
        }
        return files;
    }

    /* 递归查询子目录 */
    private static void recursiveFind(List<File> files,String filePath) {
        File root = new File(filePath);
        File[] listFiles = root.listFiles();
        for(File file : listFiles) {
            if(file.isDirectory()) {
                recursiveFind(files, file.getAbsolutePath());
            }else {
                files.add(file);
            }
        }
    }

    public static boolean tryDelete(File file) {
        if(file.exists()) {
            return file.delete();
        }
        return false;
    }

    public static boolean tryCreate(File file) {
        if(!file.exists()) {
            try {
                return file.createNewFile();
            } catch (IOException e) {
                if(log.isErrorEnabled()) {
                    log.error(String.format(CommonConstants.ERROR_PREFIX + "file '{}' create fail", file.toURI()));
                }
            }
        }
        return false;
    }
}
